import json
from datetime import datetime

from django.core.paginator import Paginator
from django.http import JsonResponse
from django.views import View
from lapi_app.models.testcase_model.testcase import Variable_local
from lapi_app.view.user_view.token_check import access_token


class Var_view_local(View):

    def post(self, request, *args, **kwargs):
        data = json.loads(request.body)
        if not access_token(data["user_id"]):
            return JsonResponse({
                "code": 1001,
                "message": "登录失效，请重新登录"
            })
        if data["local_variable_name"] == "":
            variable = Variable_local.objects.all().order_by("-id")
        else:
            variable = Variable_local.objects.filter(local_name__contains=data["local_variable_name"])
        size_page = data["size_page"]
        current_pages = data["current_page"]
        case_total = len(variable)
        var_list = []
        for var in variable:
            var_dict = {
                "local_variable_id": var.id,
                "local_variable_name": var.local_name,
                "local_variable_data": var.local_data,
                "local_variable_result": var.local_result,
                "local_variable_description": var.local_description,
                "username": var.local_user.username,
                "update_time": datetime.strftime(var.update_time, "%Y-%m-%d %H:%M:%S"),
                "create_time": datetime.strftime(var.create_time, "%Y-%m-%d %H:%M:%S")
            }
            var_list.append(var_dict)
        p = Paginator(var_list, size_page)
        page1 = p.page(current_pages)
        current_page = page1.object_list
        return JsonResponse({
            "code": 200,
            "message": "获取变量列表成功",
            "content": current_page,
            "case_total": case_total,
            "size_page": size_page,
            "current_page": current_pages
        })
